package client.main;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class MainWindow {

	private static JButton jButton = new JButton("Send");
	private static JTextField jTextArea = new JTextField();
	private static JTextArea jta1 = new JTextArea();

	private static DataOutputStream toserver;
	private static DataInputStream fromserver;
	private static Socket client;

	public static void main(String[] args) {
		window();
		sned();
	}

	private static void sned() {
		jButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				String str = jTextArea.getText().toString();
				try {
					toserver.writeUTF(str);
					toserver.flush();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		});

	}

	private static void option(String message) {
		JOptionPane.showMessageDialog(null, message, "提示", JOptionPane.INFORMATION_MESSAGE);
	}

	private static void window() {
		JFrame jFrame = new JFrame();
		JPanel jPanel = new JPanel();
		jPanel.setLayout(new BorderLayout());
		jPanel.add(jTextArea, BorderLayout.CENTER);
		jPanel.add(jButton, BorderLayout.EAST);
		jFrame.setTitle("Socket Chat Room");
		jFrame.setLayout(new BorderLayout());
		jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jFrame.add(jta1);
		jFrame.add(jPanel, BorderLayout.SOUTH);
		jFrame.setVisible(true);
		jFrame.setSize(600, 500);
		jFrame.setLocationRelativeTo(null);

		try {
			client = new Socket("localhost", 8889);
			toserver = new DataOutputStream(client.getOutputStream());
			fromserver = new DataInputStream(client.getInputStream());
			while (true) {
				String msg = fromserver.readUTF();
				if (msg != null)
					jta1.append(msg + "\n");
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
